<template>
  <div class="common-layout">
    <Header/>
    <el-container id="container">
      <el-main>
        <div id="condition">
          <el-select v-model="cinemaObj"
                     size="large"
                     placeholder="请选择影院"
                     style="width: 360px"
                     @change="handleCinemaSelect"
                     clearable>
            <el-option
                v-for="cinema in cinemaList"
                :key="cinema.cId"
                :label="cinema.cName"
                :value="cinema.cId">
              <span style="float: left">{{ cinema.cName }}</span>
              <span style="float: right;color: var(--el-text-color-secondary); font-size: 13px;">
              {{ cinema.address }}</span>
            </el-option>
          </el-select>
          <el-select v-model="hallObj"
                     size="large"
                     placeholder="请选择影厅"
                     style="width: 360px"
                     @change="handleHallSelect"
                     clearable>
            <el-option
                v-for="hall in hallList"
                :key="hall.hId"
                :label="hall.hName"
                :value="hall.hId"
                clearable>
              <span style="float: left">{{ hall.hName }}</span>
              <span style="float: right;color: var(--el-text-color-secondary); font-size: 13px;">
              {{ hall.capacity }}</span>
            </el-option>
          </el-select>
          <el-select
              v-model="seatObj"
              filterable
              multiple
              clearable
              placeholder="请选择座位，支持多选和模糊搜索"
              style="width: 300px"
              size="large"
              @change="handleSeatSelect"
          >
            <el-option
                v-for="seat in seatList"
                :key="seat.value"
                :label="seat.value"
                :value="seat.value"
            />
          </el-select>
          <el-input
              v-model="movieName"
              style="width: 240px"
              placeholder="请输入电影名称"
              :prefix-icon="Search"
              size="large"
              @keyup.enter="handleMovieNameSearch"
          />
          <el-date-picker
              v-model="beginAndEndDay"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="shortcuts"
              size="large"
              @change="handleDateChange"
          />
        </div>

        <div id="orderTableDiv">
          <el-table
              id="orderTable"
              :data="orderTableData"
              border
              size="large"
              table-layout="fixed">
            <el-table-column prop="oid" label="订单id" v-if="false"/>
            <el-table-column prop="uid" label="用户id" v-if="false"/>
            <el-table-column prop="cId" label="影院id" v-if="false"/>
            <el-table-column prop="soId" label="场次id" v-if="false"/>
            <el-table-column prop="cinemaName" label="影院名称"/>
            <el-table-column prop="address" label="影院地址"/>
            <el-table-column prop="hallName" label="影厅名称"/>
            <el-table-column prop="seat" label="座位"/>
            <el-table-column prop="movieName" label="电影名称"/>
            <el-table-column prop="beginTime" label="开始时间"/>
            <el-table-column prop="endTime" label="结束时间"/>
            <el-table-column prop="oCreatedAt" label="订单创建时间"/>
            <el-table-column prop="payAt" label="支付时间"/>
            <el-table-column prop="amount" label="金额"/>
            <el-table-column prop="orderStatus" label="订单状态">
              <template #default="scope">
                <el-tag
                    :type="getTagType(scope.row.orderStatus)"
                    :size=" 'medium'"
                >{{ getStatusText(scope.row.orderStatus) }}
                </el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="orderNo" label="订单号"/>
            <el-table-column prop="operation" label="操作">
              <template #default="scope">
                <el-button size="small" @click="handleShowQrCode(scope.row)" type="success" style="width: 70px">
                  查看券码
                </el-button>
                <el-button size="small" @click="handleRefund(scope.row)" type="danger" style="width: 50px">
                  退款
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-dialog
            title="二维码展示"
            v-model="qrCodeVisible"
            width="300"
            align-center>
          <div style="text-align: center;">
            <el-text style="margin:20px auto">您可以右键→将图像另存为，来保存劵码图片</el-text>
            <qrcode-vue :value="qrCodeText" :size="200" @change="qrCodeChange"/>
          </div>
          <template #footer>
        <span class="dialog-footer">
          <el-button @click="qrCodeVisible = false">关闭</el-button>
        </span>
          </template>
        </el-dialog>
      </el-main>
      <el-footer>
        <div id="commentPage">
          <el-pagination
              style="float:right"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :current-page="currentPage"
              :disabled="false"
              :total="totalCount"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              background layout="total, sizes, prev, pager, next, jumper"/>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script setup>
import {ElNotification} from "element-plus";
import request from "@/request.js";
import {request2} from "@/request.js";
import qs from 'qs'
import {ref, reactive, onMounted, onBeforeUnmount} from "vue";
import {Lock, User, Cellphone, UserFilled, Search} from "@element-plus/icons-vue";
import SessionStorage from "@/SessionStorage.js";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
import moment from "moment";

const baseIp = import.meta.env.VITE_APP_API_URL;

const movieName = ref("");
const router = useRouter();
const loginUser = SessionStorage.getItem("loginUser");

const route = useRoute();
const midWith = route.params.mid;
console.log("从电影详情跳转之后，携带的mid为：" + midWith);
// 分页插件
const currentPage = ref(1);
const pageSize = ref(5);
const totalCount = ref(0);

// 选择电影院下拉框
const cinemaObj = ref('')
const hallObj = ref('')
const seatObj = ref([])

// 下拉框内容列表
const cinemaList = ref([{
  cId: -1,
  cName: 'Beijing',
  address: 'Beijing',
}]);
// 查询电影院列表
const cinemaAndHallList = reactive([{
  cId: -1,
  cName: "",
  address: "",
  hallList: [{
    hId: -1,
    cId: -1,
    hName: "",
    hCapacity: "",
    rowNo: -1,
    lineNo: -1,
  }]
}])

// 选中cinema之后，联动的hallList
const hallList = ref([{
  hId: -1,
  hName: '',
  capacity: '',
}])
// 查询出来的seat列表
const seatList = reactive([
  {
    value: null
  }
])

// 查询订单的查询参数
const queryDto = reactive({
  uid: loginUser.uid,
  cId: cinemaObj.value,
  hId: hallObj.value,
  movieName: movieName.value,
  seatList: [],
  beginDay: null,
  endDay: null,
  pageNo: currentPage.value,
  pageSize: pageSize.value
})
const searchCinemaList = async () => {
  request2({
    url: "/cinema/selectAll",
    method: "post",
  }).then(res => {
    if ('200' === res.code && res.data != null) {
      console.log('查询所有电影院成功！');
      console.log('查询所有电影院接口返回的数据：', res.data);
      const cinemaAndHallListReturn = res.data;
      // 清空后端返回的影院demo数据
      cinemaAndHallList.splice(0, cinemaAndHallList.length);
      // 清空影院下拉框数据
      cinemaList.value.splice(0, cinemaList.value.length);
      cinemaAndHallListReturn.forEach(item => {
        cinemaAndHallList.push(item);
        let select = reactive({
          cId: -1,
          cName: "",
          address: ""
        })
        select.cId = item.cId;
        select.cName = item.cName;
        select.address = item.address;
        cinemaList.value.push(select);
      })
    }
  })
}
searchCinemaList();
// 查询场次座位信息
const searchSeatList = (hId) => {
  const queryDto = reactive({
    hsId: null,
    hId: hId,
    rowIndex: null,
    lineIndex: null,
    pageNo: null,
    pageSize: null
  })
  console.log("queryDto的hId为：" + queryDto.hId)
  request2({
    url: "/hallSeat/selectCondition",
    method: "post",
    data: queryDto
  }).then(res => {
    if ('200' === res.code && res.data != null) {
      console.log('查询场次座位信息成功！');
      console.log('查询场次座位信息接口返回的数据：', res.data);
      const hallInfoQuery = res.data.list;
      seatList.splice(0, seatList.length);
      hallInfoQuery.forEach(hall => {
        const seatObj =
            {
              value: hall.rowIndex + "-" + hall.lineIndex
            }
        seatList.push(seatObj);
      })
    }
  })
}

const handleCinemaSelect = () => {
  console.log("电影院选择框发生了改变！");
  console.log("当前选中值为：" + cinemaObj.value)
  if (cinemaObj.value !== null && cinemaObj.value !== '') {
    queryDto.cId = cinemaObj.value;
    searchOrders();
    cinemaAndHallList.forEach(item => {
      if (item.cId === cinemaObj.value) {
        // 清空影院下拉框数据
        hallList.value.splice(0, hallList.value.length);
        item.hallList.forEach(item2 => {
          let select2 = reactive({
            hId: -1,
            hName: "",
            capacity: ""
          })
          select2.hId = item2.hId;
          select2.hName = item2.hName;
          select2.capacity = "容量：" + item2.hCapacity + "个";
          hallList.value.push(select2);
        })
      }
    })
  }
}
const handleHallSelect = () => {
  console.log("影厅选择框发生了改变！");
  console.log("当前选中值为：" + hallObj.value)
  queryDto.hId = hallObj.value;
  searchSeatList(hallObj.value);
  searchOrders();
}
const handleSeatSelect = () => {
  console.log("座位选择框发生了改变！");
  console.log("当前选中值为：" + seatObj.value)
  queryDto.seatList.splice(0, queryDto.seatList.length);
  queryDto.seatList.push(...seatObj.value);
  searchOrders();
}
const handleMovieNameSearch = () => {
  console.log(movieName.value);
  queryDto.movieName = movieName.value;
  searchOrders();
}

const beginAndEndDay = ref("");
const shortcuts = [
  {
    text: '过去一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '过去一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '过去三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 订单表格
// 用于存储当前页的数据
const orderTableData = reactive([])


// 已经开场则不允许查看券码，每分钟执行一次

console.log("查询订单的参数是：" + JSON.stringify(queryDto))
const searchOrders = () => {
  request2({
    url: "/order/selectCondition",
    method: "post",
    data: queryDto
  }).then(res => {
    if ('200' === res.code && res.data != null) {
      console.log('查询订单成功！');
      console.log('查询订单接口返回的数据：', res.data);

      totalCount.value = res.data.totalCount;
      pageSize.value = res.data.pageSize;

      orderTableData.splice(0, orderTableData.length);
      // 更新当前页数据
      orderTableData.push(...res.data.list);

    } else {
      ElNotification({
        type: 'error',
        message: res.msg
      })
    }
  })
}
searchOrders();

const handleCurrentChange = async (newPage) => {
  console.log("pageNo修改为第" + newPage + "页！");
  currentPage.value = newPage;
  queryDto.pageNo = newPage;
  searchOrders();
};

// 处理每页显示数量改变的方法
const handleSizeChange = (newSize) => {
  console.log("pageSize修改为每页" + newSize + "条！");
  pageSize.value = newSize;
  currentPage.value = 1;

  queryDto.pageSize = newSize;
  searchOrders();
};

const handleSelectSeat = (row) => {
  const soId = row.soId;
  console.log("购票的场次id为：" + soId);

  router.push({name: "BuyTicket", params: {soId: soId}});
}

const handleDateChange = () => {
  console.log("购买日期的选择框发生了改变！");
  console.log("当前选中值为：" + beginAndEndDay.value)
  queryDto.beginDay = moment(beginAndEndDay.value[0]).format("YYYY-MM-DD");
  queryDto.endDay = moment(beginAndEndDay.value[1]).format("YYYY-MM-DD");
  searchOrders();
}

// 二维码展示
const qrCodeVisible = ref(false);
const qrCodeText = ref("111111111111");
const handleShowQrCode = (row) => {
  // 判断是否购买+是否未开场
  if (row.orderStatus !== '20') {
    ElNotification.error("订单未支付成功！")
    return;
  } else if (!moment().isBefore(moment(row.beginTime))) {
    ElNotification.error("场次已开场，无法查看券码！")
    return;
  }

  qrCodeText.value = row.qrCodeValue;
  qrCodeVisible.value = true;
}
const qrCodeChange = (dataUrl) => {
  this.dataUrl = dataUrl
}
// 退票
const handleRefund = (row) => {
  axios.post(
      baseIp + ":9090/alipay/refund?oid=" + row.oid,
      null,
      {headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}}
  ).then(res => {
    console.log(res.data);
    if ('200' === res.data.code) {
      ElNotification.success(res.data.msg);
      window.location.reload();
    } else {
      ElNotification({
        type: 'error',
        message: res.data.msg
      })
    }
  })
}
const getTagType = (orderStatus) => {
  if (orderStatus === '10') {
    return 'warning';
  } else if (orderStatus === '20') {
    return 'success';
  } else if (orderStatus === '30') {
    return 'primary';
  } else if (orderStatus === '80') {
    return 'danger';
  }
};
const getStatusText = (status) => {
  switch (status) {
    case '10':
      return '未支付';
    case '20':
      return '已支付';
    case '30':
      return '退票';
    case '80':
      return '异常';
  }
};
</script>

<style scoped>


#condition {
  display: flex;
  justify-content: center;
  align-items: center;
}

#condition .el-select {
  margin: 10px 20px;
}

#condition .el-input {
  margin: 10px 20px;
}

#orderTableDiv {
  margin-top: 20px;
  width: 100%;
}
</style>
